import './json2.min'
import './jquery-1.8.3.min'
import '../layer/layer'

/*
	版权所有 2009-2021 荆门泽优软件有限公司
	保留所有权利
	官方网站：http://www.ncmem.com
	产品首页：http://www.ncmem.com/webapp/scp2/index.aspx
	控件下载：http://www.ncmem.com/webapp/scp2/pack.aspx
	示例下载：http://www.ncmem.com/webapp/scp2/versions.aspx
	联系邮箱：1085617561@qq.com
	联系QQ：1085617561
	版本：2.1.2
*/
function debugMsg (txt) {
  $('#msg').append(txt + '<br/>')
}

//全局对象
var ScreenCaptureError = {
  '0': '就绪'
  , '1': '发送数据错误'
  , '2': '接收数据错误'
  , '3': '域名未授权或为空'
  , '4': '公司未授权或为空'
  , '5': 'nat app error'
}

var LanguageZhCn = {
  'CapForm': '截屏选择窗口'
  , 'CapFormTitle': '选择截屏窗口'
  , 'CapFormTip': '请将您想要截取的窗口调整到最前'
  , 'BtnOk': '确定'
  , 'BtnCancel': '取消'
  , 'RectSuze': '区域大小'
  , 'CurRGB': '当前RGB'
  , 'QuckCap': '双击可以快速完成截图'
}
var LanguageEn = {
  'CapForm': 'Capture Form Selecter'
  , 'CapFormTitle': 'Choose Capture Form'
  , 'CapFormTip': 'Please set the window to the front which you want to intercept resize'
  , 'BtnOk': 'Ok'
  , 'BtnCancel': 'Cancel'
  , 'RectSuze': 'Rect Size'
  , 'CurRGB': 'Current RGB'
  , 'QuckCap': 'Double-click can be quickly completed Screenshot'
}
var LanguageZhTw = {
  'CapForm': '截屏選擇視窗'
  , 'CapFormTitle': '選擇截屏視窗'
  , 'CapFormTip': '請將您想要截取的視窗調整到最前'
  , 'BtnOk': '確定'
  , 'BtnCancel': '取消'
  , 'RectSuze': '區域大小'
  , 'CurRGB': '當前RGB'
  , 'QuckCap': '雙擊可以快速完成截圖'
}

export function WebServer (mgr) {
  var _this = this
  // 创建一个Socket实例
  this.socket = null
  this.tryConnect = true

  this.run = function () {
    if (typeof navigator.msLaunchUri != 'undefined') {
      console.log(mgr.Config.edge.protocol + '://' + mgr.Config.edge.port)
      //up6://9006
      navigator.msLaunchUri(mgr.Config.edge.protocol + '://' + mgr.Config.edge.port, function () {
        console.log('应用打开成功')
      }, function () {
        console.log('启动失败')
      })
    }
  }
  this.runChr = function () {
    var protocol = mgr.Config.edge.protocol + '://' + mgr.Config.edge.port
    var html = '<iframe id=\'scp-uri-fra\' width=1 height=1 src=\'' + protocol + '\'></iframe>'
    $('#scp-uri-fra').remove()
    $(document.body).append(html)
  }
  this.connect = function () {
    if (!_this.tryConnect) return
    var con = new WebSocket('ws://127.0.0.1:' + mgr.Config.edge.port)
    console.log('开始连接服务:' + 'ws://127.0.0.1:' + mgr.Config.edge.port)

    // 打开Socket
    con.onopen = function (event) {
      _this.socket = con
      _this.tryConnect = false
      console.log('服务连接成功')

      // 监听消息
      con.onmessage = function (event) {
        mgr.recvMessage(event.data)
      }

      // 监听Socket的关闭
      con.onclose = function (event) {
      }
    }
    con.onerror = function (event) {
      _this.run()
      console.log('连接失败')
    }
  }
  this.close = function () {
    if (this.socket) {
      this.socket.close(1000, 'close')
    }
  }
  this.send = function (p) {
    if (this.socket) this.socket.send(JSON.stringify(p))
  }
}

/*
	截屏对象管理类，提供常用配置功能
	参数
*/
export function CaptureManager () {
  var _this = this
  this.StateType = {
    Ready: 0
    , Posting: 1
    , Stop: 2
    , Error: 3
    , GetNewID: 4
    , Complete: 5
    , WaitContinueUpload: 6
    , None: 7
    , Waiting: 8
  }
  _this.State = _this.StateType.None
  this.scpFF = null
  this.scpIE = null
  this.pluginInited = false
  this.ui = { panel: null, ico: null, img: null, msg: null, per: null, setup: null, dlg: null }
  this.event = {
    postComplete: function (src) {
      var html = '<img src=\'' + src + '\'/>'
      tinyMCE.activeEditor.execCommand('mceInsertRawHTML', false, html)
    }, hotKey: function () {
    }
  }

  //全局配置信息
  this.Config = {
    event: {},
    'PostUrl': 'http://www.ncmem.com/upload.aspx'
    , 'EncodeType': 'utf-8'
    , 'Version': '1,4,74,5817'
    , 'Company': '荆门泽优软件有限公司'
    , 'License2': ''
    , 'Debug': false//是否打开调试模式
    , 'LogFile': 'F:\\log.txt'//日志文件路径
    , 'FileFieldName': 'img'//自定义图片文件字段名称。
    , 'ImageMatch': ''//服务器返回数据匹配模式，正则表达式，提取括号中的地址
    , 'ImageUrl': ''//自定义图片地址，格式"{url}"，{url}为固定变量，在此变量前后拼接图片路径，此变量的值为posturl返回的图片地址
    , 'Language': 'zhcn'//语言设置，en,zhcn,tw
    , 'LanCur': LanguageZhCn//语言设置
    , 'Quality': 100//jpg图片质量，仅对jpg格式有效
    , 'ShowForm': true//是否显示截屏提示窗口
    , 'ImageType': 'png'//图片上传格式。png,jpg,bmp
    , 'NameCrypto': 'crc'//名称生成算法。crc,md5,sha1,uuid
    , 'IcoPath': '/scp/uploading.gif'
    , 'Cookie': ''
    , 'HotKey': 'Ctrl+Alt+Q'
    , 'Authenticate': { 'type': 'ntlm', 'name': '', 'pass': '' }//域环境信息
    , 'UI': {
      selector: {
        border: '#DC143C'//选框边框
      },
      font: ['21', '22', '23', '24']
    }
    //x86
    , ie: {
      part: { clsid: '9767D337-E10A-4319-8854-E4B0FB635274', name: 'Xproer.ScreenCapturePro2' }
      , path: './scp.cab'
    }
    //x64
    , ie64: {
      part: { clsid: '399B59CE-646E-4430-9000-138DF6515306', name: 'Xproer.ScreenCapturePro2x64' }
      , path: './scp64.cab'
    }
    , firefox: { name: '', type: 'application/npScpPro2', path: './scp.xpi' }
    , chrome: { name: 'npScpPro2', type: 'application/npScpPro2', path: './scp.crx' }
    //Chrome 45
    , chrome45: { name: 'com.xproer.down2', path: './scp.crx' }
    , exe: { path: './scp.exe' }
    , edge: { protocol: 'scp2', port: 9800, visible: false }
    , 'Fields': { 'uname': 'test', 'upass': 'test', 'uid': '0', 'fid': '0' }
  }
  $.extend(this.event, this.Config.event)
  this.postError = function (json) {
    this.ui.msg.html(
      ScreenCaptureError[json.value] + '<br/>' +
      'PostUrl:' + this.Config['PostUrl'] + '<br/>' +
      'License:' + this.Config['License'] + '<br/>' +
      'License2:' + this.Config['License2'] + '<br/>' +
      '当前Url:' + window.location.href)
    this.ui.per.text('')
  }
  this.postProcess = function (json) {
    this.ui.per.text(json.percent)
  }
  this.postComplete = function (json) {
    this.ui.per.text('100%')
    this.ui.msg.text('上传完成')
    this.CloseMsg() //隐藏信息层
    this.event.postComplete(json.value)
  }
  this.runComplete = function (json) {
    this.Browser.exitCheck()
  }
  this.loadComplete = function (json) {
    this.pluginInited = true
    var needUpdate = true
    if (typeof (json.version) != 'undefined') {
      if (json.version == this.Config.Version) {
        needUpdate = false
      }
    }
    if (needUpdate) {
      this.need_update()
    } else {
      this.CloseMsg()
    }
  }
  this.load_complete_edge = function (json) {
    this.pluginInited = true
    this.edge_load = true
    this.SafeCheck()
    this.CloseMsg()
    _this.app.init()
  }
  this.afterCapture = function (json) {
    this.OpenMsg()/*打开信息面板*/
  }
  this.hotKey = function (json) {
    this.event.hotKey()
  }
  this.state_message = function (json) {
    alert(json.msg)
  }
  this.recvMessage = function (str) {
    var json = JSON.parse(str)
    if (json.name == 'AfterCapture') {
      _this.afterCapture(json)
    } else if (json.name == 'HotKey') {
      _this.hotKey(json)
    } else if (json.name == 'state_message') {
      _this.state_message(json)
    } else if (json.name == 'post_process') {
      _this.postProcess(json)
    } else if (json.name == 'post_error') {
      _this.postError(json)
    } else if (json.name == 'post_complete') {
      _this.postComplete(json)
    } else if (json.name == 'run_complete') {
      _this.runComplete(json)
    } else if (json.name == 'run_error') {
      _this.postError(json)
    } else if (json.name == 'load_complete') {
      _this.loadComplete(json)
    } else if (json.name == 'load_complete_edge') {
      _this.load_complete_edge(json)
    }
  }

  var browserName = navigator.userAgent.toLowerCase()
  this.ie = browserName.indexOf('msie') > 0
  //IE11
  this.ie = _this.ie ? _this.ie : browserName.search(/(msie\s|trident.*rv:)([\w.]+)/) != -1
  this.firefox = browserName.indexOf('firefox') > 0
  this.chrome = browserName.indexOf('chrome') > 0
  this.chrome45 = false
  this.chrVer = navigator.appVersion.match(/Chrome\/(\d+)/)
  this.edge = navigator.userAgent.indexOf('Edge') > 0
  this.edgeApp = new WebServer(this)
  this.app = {
    ins: null
    , edgeApp: null
    , Config: null
    , queueCount: 0
    , checkFF: function () {
      var mimetype = navigator.mimeTypes
      if (typeof mimetype == 'object' && mimetype.length) {
        for (var i = 0; i < mimetype.length; i++) {
          var enabled = mimetype[i].type == this.Config.firefox.type
          if (!enabled) enabled = mimetype[i].type == this.Config.firefox.type.toLowerCase()
          if (enabled) return mimetype[i].enabledPlugin
        }
      } else {
        mimetype = [this.Config.firefox.type]
      }
      if (mimetype) {
        return mimetype.enabledPlugin
      }
      return false
    }
    , Setup: function () {
      //文件夹选择控件
      acx += '<object id="downPart" classid="clsid:' + this.Config.ClsidPart + '"'
      acx += ' codebase="' + this.Config.CabPath + '" width="1" height="1" ></object>'

      $('body').append(acx)
    }
    , init: function () {
      var param = { name: 'init', config: this.Config }
      this.postMessage(param)
    }
    , initNat: function () {
      if (!this.chrome45) return
      this.exitEvent()
      document.addEventListener('Down3EventCallBack', function (evt) {
        this.recvMessage(JSON.stringify(evt.detail))
      })
    }
    , initEdge: function () {
      this.edgeApp.run()
    }
    , capture: function (opt) {
      var param = $.extend({}, opt, { name: 'capture' })
      this.postMessage(param)
    }
    , captureScreen: function (opt) {
      var param = $.extend({}, opt, { name: 'capture_screen' })
      this.postMessage(param)
    }
    , captureRect: function (left, top, width, height) {
      var param = { name: 'capture_rect', x: left, y: top, w: width, h: height }
      this.postMessage(param)
    }
    , paste: function () {
      var param = { name: 'paste' }
      this.postMessage(param)
    }
    , exit: function () {
      var par = { name: 'exit' }
      var evt = document.createEvent('CustomEvent')
      evt.initCustomEvent(this.entID, true, false, par)
      document.dispatchEvent(evt)
    }
    , exitEvent: function () {
      var obj = this
      $(window).bind('beforeunload', function () {
        obj.exit()
      })
    }
    , postMessage: function (json) {
      try {
        this.ins.parter.postMessage(JSON.stringify(json))
      } catch (e) {
        console.log('调用postMessage失败，请检查控件是否安装成功')
      }
    }
    , postMessageNat: function (par) {
      var evt = document.createEvent('CustomEvent')
      evt.initCustomEvent(this.entID, true, false, par)
      document.dispatchEvent(evt)
    }
    , postMessageEdge: function (par) {
      this.edgeApp.send(par)
    }
  }
  this.app.edgeApp = this.edgeApp
  this.app.Config = this.Config
  this.app.ins = this
  if (this.edge) {
    this.ie = this.firefox = this.chrome = this.chrome45 = false
  }

  this.pluginLoad = function () {
    if (!this.pluginInited) {
      if (this.edge) {
        this.edgeApp.connect()
      }
    }
  }
  this.pluginCheck = function () {
    if (!this.pluginInited) {
      alert('控件没有加载成功，请安装控件或等待加载。')
      this.pluginLoad()
      return false
    }
    return true
  }
  //Win64
  if (window.navigator.platform == 'Win64') {
    jQuery.extend(this.Config.ie, this.Config.ie64)
  } //Firefox
  if (this.firefox) {
    this.edge = true
    this.app.postMessage = this.app.postMessageEdge
    this.edgeApp.run = this.edgeApp.runChr
  } //chrome
  else if (this.chrome) {
    this.app.check = this.app.checkFF
    jQuery.extend(this.Config.firefox, this.Config.chrome)
    this.edge = true
    this.app.postMessage = this.app.postMessageEdge
    this.edgeApp.run = this.edgeApp.runChr
  } else if (this.edge) {
    this.app.postMessage = this.app.postMessageEdge
  }

  this.GetHtml = function () {
    //ff
    var html = ''
    //ie
    //html += '<div style="display: none">';
    html += '<object name="scpIE" classid="clsid:' + this.Config.ie.part.clsid + '"'
    html += ' codebase="' + this.Config.ie.path + '#version=' + this.Config['Version'] + '" width="1" height="1"></object>'
    if (this.edge) html = ''
    //html += '</div>';
    //
    html += '<div name="ui-scp" class="panel-scp">\
	                <img name="ico" alt="" src="/ScreenCapture/process.gif" /><span name="msg">图片上传中...</span><span name="per">10%</span>\
	            </div>'
    //安装提示
    html += '<div name="ui-setup" class="panel-scp panel-setup"></div>'
    return html
  }

  //安全检查，在用户关闭网页时自动停止所有上传任务。
  this.SafeCheck = function (event) {
    //$(window).bind("beforeunload", function (event) {});
    $(window).bind('unload', function () {
      if (this.edge) _this.edgeApp.close()
    })
  }
  this.setup_tip = function () {
    var dom = this.ui.setup.html('控件加载中，如果未加载成功请先<a name=\'w-exe\' style=\'color: blue;text-decoration: underline\'>安装控件</a>')
    var lnk = dom.find('a[name="w-exe"]')
    lnk.attr('href', this.Config.exe.path)

    this.ui.dlg = layer.open({
      type: 1,
      title: '截屏图片上传进度',
      closeBtn: 1,
      area: ['170px', '113px'],
      content: this.ui.setup,
      shadeClose: false,
    })
  }
  this.need_update = function () {
    var dom = this.ui.setup.html('发现新版本，请<a name=\'w-exe\' href=\'#\'>更新</a>')
    var lnk = dom.find('a[name="w-exe"]')
    lnk.attr('href', this.Config.exe.path)
  }

  //加载到document.body中
  this.loadAuto = function () {
    if (!ScreenCapture.inited) {
      var ui = $(document.body).append(this.GetHtml())
      this.initUI(ui)
    }
    ScreenCapture.inited = true
  }

  //加截到指定对象内部
  this.load_to = function (oid) {
    if (!ScreenCapture.inited) {
      var ui = $('#' + oid).append(this.GetHtml())
      this.initUI(ui)
    }
    ScreenCapture.inited = true
  }

  this.initUI = function (ui) {
    this.parter = ui.find('embed[name="scpFF"]').get(0)
    this.scpIE = ui.find('object[name="scpIE"]').get(0)
    this.ui.panel = ui.find('div[name="ui-scp"]')
    this.ui.ico = ui.find('img[name="ico"]').attr('src', this.Config['IcoPath'])
    this.ui.msg = ui.find('span[name="msg"]')
    this.ui.per = ui.find('span[name="per"]')
    this.ui.setup = ui.find('div[name="ui-setup"]')

    $(function () {
      if (!_this.edge) {
        if (_this.ie) {
          _this.parter = _this.scpIE
        }
        _this.parter.recvMessage = _this.recvMessage
      }
      _this.setup_tip()
      if (_this.edge) {
        _this.edgeApp.connect()
      } else {
        _this.app.init()
      }
    })
  }

  //截屏函数
  this.Capture = function () {
    if (!this.pluginCheck()) return
    var opt = { autoHide: false }//自动隐藏当前窗口
    this.app.capture(opt)
  }
  this.Capture2 = function () {
    if (!this.pluginCheck()) return
    var opt = { form: this.Config.ShowForm }//不显示提示窗口
    this.app.capture(opt)
  }
  //自动隐藏当前窗口
  this.CaptureHide = function () {
    if (!this.pluginCheck()) return
    var opt = { autoHide: true }//自动隐藏当前窗口
    this.app.capture(opt)
  }

  /**
   * 截取整个屏幕
   * @param bool edit 是否启动编辑
   */
  this.CaptureScreen = function (edit) {
    if (!this.pluginCheck()) return
    this.app.captureScreen({ 'edit': edit })
  }
  //截取指定区域
  this.CaptureRect = function (x, y, w, h) {
    if (!this.pluginCheck()) return
    this.app.captureRect(x, y, w, h)
  }
  this.OpenMsg = function () {
    _this.ui.msg.text('图片上传中...')
    this.ui.dlg = layer.open({
      type: 1,
      title: '截屏图片上传进度',
      closeBtn: 1,
      area: ['170px', '113px'],
      content: _this.ui.panel,
      shadeClose: false,
    })
  }
  this.Paste = function () {
    if (!this.pluginCheck()) return
    this.app.paste()
  }
  this.CloseMsg = function () {
    layer.close(this.ui.dlg)
  }
}

//用法：
/**
 * ScreenCapture.getInstance().load();
 */
export var ScreenCapture = {
  instance: null,
  inited: false,
  getInstance: function (cfg) {
    if (this.instance == null) {
      this.instance = new CaptureManager()
      $.extend(this.instance.Config, cfg)
      window.ScreenCapture = ScreenCapture
    }
    return this.instance;
  }
};
